using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Traceability.API.Dtos;

namespace Traceability.API.Services
{
    public class JwtService
    {
        private readonly IConfiguration _configuration;

        public JwtService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 生成JWT Token
        /// </summary>
        /// <param name="userDto">用户信息</param>
        /// <returns>JWT Token</returns>
        public string GenerateToken(UserDto userDto)
        {
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            var credentials = new SigningCredentials(new SymmetricSecurityKey(secretByte), SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userDto.UserId.ToString()),
                new Claim(ClaimTypes.Name, userDto.UserName),
                new Claim(ClaimTypes.Role, userDto.RoleName),
                new Claim("UserNickName", userDto.UserNickName ?? string.Empty),
                new Claim("RoleId", userDto.RoleId.ToString()),
                new Claim("UserId", userDto.UserId.ToString())
            };

            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                expires: DateTime.Now.AddHours(24), // Token有效期24小时
                signingCredentials: credentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 验证JWT Token
        /// </summary>
        /// <param name="token">JWT Token</param>
        /// <returns>验证结果</returns>
        public bool ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");

            try
            {
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte),
                    ValidateIssuer = true,
                    ValidIssuer = "BeiJingBW",
                    ValidateAudience = true,
                    ValidAudience = "BeiJingBW",
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 从Token中获取用户ID
        /// </summary>
        /// <param name="token">JWT Token</param>
        /// <returns>用户ID</returns>
        public int GetUserIdFromToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtToken = tokenHandler.ReadJwtToken(token);
            
            var userIdClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
            {
                return userId;
            }
            
            return 0;
        }

        /// <summary>
        /// 从Token中获取角色信息
        /// </summary>
        /// <param name="token">JWT Token</param>
        /// <returns>角色名称</returns>
        public string GetRoleFromToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtToken = tokenHandler.ReadJwtToken(token);
            
            var roleClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);
            return roleClaim?.Value ?? string.Empty;
        }
    }
} 